<template>
	<view class="zzx-calendar">
		<!-- <view class="calendar-heander">
			{{timeStr}}
			<view class="back-today" @click="goback" v-if="showBack">
				返回今日
			</view>
		</view> -->
		<!-- 日历顶部信息 -->
		<view class="calendar_info">
			<text class="title">
				{{timeStr}}
			</text>
			<u-icon class="icon" name="more-dot-fill"
				style="font-size: 20px;font-weight: bolder;margin-left: auto;"></u-icon>
			<view v-show="showBackToTodayBtn" class="write_btn" @tap="goback()">
				<u-icon class="icon" name="arrow-leftward"></u-icon>
			</view>
		</view>
		<view class="calendar-weeks">
			<view class="calendar-week" v-for="(week, index) in weeks" :key="index">
				{{week}}
			</view>
		</view>
		<view style="float: left;width: 100%;height: 100%;">
			<swiper :style="fullHeight" :indicator-dots="false" :autoplay="false" :duration="duration"
				:current="current" @change="changeSwp" :circular="true">

				<swiper-item v-for="sitem in swiper" :key="sitem" class="swiper_item">
					<view class="calendar-days">
						<template v-if="sitem === current">
							<!-- <view class="calendar-day" style="width: 64rpx;" v-if="showWeek">周</view> -->
							<view class="calendar-day" v-for="(item,index) in days" :key="index" :class="{
								'day-hidden': !item.show
							}" @click="clickItem(item)">
								<view class="date" :class="[
									item.isToday ? todayClass : '',
									item.fullDate === selectedDate ? checkedClass : '']">
									{{item.time.getDate()}}
								</view>
								<view class="dot-show" v-if="item.info" :style="dotStyle">
								</view>
							</view>
						</template>
						<template v-else>
							<template v-if="current - sitem === 1 || current-sitem ===-2">
								<view class="calendar-day" v-for="(item,index) in predays" :key="index" :class="{
										'day-hidden': !item.show}">
									<view class="date" :class="[item.isToday ? todayClass : '']">
										{{item.time.getDate()}}
									</view>
								</view>
							</template>
							<template v-else>
								<view class="calendar-day" v-for="(item,index) in nextdays" :key="index" :class="{
										'day-hidden': !item.show}">
									<view class="date" :class="[item.isToday ? todayClass : '']">
										{{item.time.getDate()}}
									</view>
								</view>
							</template>
						</template>
					</view>

					<!--  =====================下面是内容========================= -->
					<scroll-view scroll-y style="float:left;z-index: 999999;height:75%;">
						<view style="width: 100%;float: left;margin-top: 20px;">
							
							<!-- 习惯 -->
							<view style="width: 100%;float:left;">
								<view class="itembox" v-for="(weekItem, indexMid) in 7" :key="indexMid">
									<view v-for="(itemMin, index) in arrThingsJson[indexMid]">
										<view class="itemTd" v-if="itemMin.type == 'habit'" @click="checkThisItem(itemMin)" :class="itemMin.status == 1?'opacityClass':''"
											style="background-color:#BEF2BD;">
											<text :class="itemMin.status == 1?'tn-icon-check':'tn-icon-circle'"></text>
											<text :class="itemMin.status == 1?'linethrough':''">{{itemMin.name}}</text>
										</view>
									</view>
								</view>
							</view>
							<!-- 目标 -->
							<view style="width: 100%;float:left;">
								<view class="itembox" v-for="(weekItem, indexMid) in 7" :key="indexMid">
									<view v-for="(itemMin, index) in arrThingsJson[indexMid]">
										<view class="itemTd" v-if="itemMin.type == 'target'" :class="itemMin.status == 1?'opacityClass':''"
											style="background-color:#E2C4FF;">
											<text :class="itemMin.status == 1?'tn-icon-check':'tn-icon-circle'"></text>
											<text :class="itemMin.status == 1?'linethrough':''">{{itemMin.name}}</text>
										</view>
									</view>
								</view>
							</view>
							<!-- 事项 -->
							<view style="width: 100%;float:left;">
								<view class="itembox" v-for="(weekItem, indexMid) in 7" :key="indexMid">
									<view v-for="(itemMin, index) in arrThingsJson[indexMid]">
										<view class="itemTd" v-if="itemMin.type == 'matter'" :class="itemMin.status == 1?'opacityClass':''"
											style="background-color:#A9D5FC;">
											<text :class="itemMin.status == 1?'tn-icon-check':'tn-icon-circle'"></text>
											<text :class="itemMin.status == 1?'linethrough':''">{{itemMin.name}}</text>
										</view>
									</view>
								</view>
							</view>
							<!-- 倒数日 -->
							<view style="width: 100%;float:left;">
								<view class="itembox" v-for="(weekItem, indexMid) in 7" :key="indexMid">
									<view v-for="(itemMin, index) in arrThingsJson[indexMid]">
										<view class="itemTd" v-if="itemMin.type == 'event'" :class="itemMin.status == 1?'opacityClass':''"
											style="background-color:#FFE4BD;">
											<text :class="itemMin.status == 1?'tn-icon-check':'tn-icon-circle'"></text>
											<text :class="itemMin.status == 1?'linethrough':''">{{itemMin.name}}</text>
										</view>
									</view>
								</view>
							</view>

						</view>
					</scroll-view>
					<!-- =====================内容结束========================= -->
				</swiper-item>
			</swiper>

		</view>
		
		<tn-popup v-model="show_popup_center" mode="center" width="650rpx" :borderRadius="20" :zIndex="10">
			<view class="container">
				<view class="row">
					<view class="category-item" @click="goToCategory()">
						<u-button class="save_btn">跳转详情</u-button>
					</view>
					<view class="category-item" @click="goToCategory()">
						<!-- <image class="category-icon" :src="category.icon"></image> -->
						<u-button class="save_btn">标记完成</u-button>
					</view>
					
				</view>
			</view>
		</tn-popup>
	</view>
</template>

<script>
	import {
		gegerateDates,
		dateEqual,
		formatDate
	} from './generateDates.js';

	export default {
		props: {
			duration: {
				type: Number,
				default: 500
			},
			dotList: {
				type: Array, /// 打点日期列表
				default () {
					return []
				}
			},
			showBack: {
				type: Boolean, // 是否返回今日
				default: false
			},
			showWeek: {
				type: Boolean, // 是否显示week
				default: false
			},
			// showChangeMode: {
			// 	type: Boolean, // 是否显示切换模式
			// 	default: false
			// },
			todayClass: {
				type: String, // 今日的自定义样式class
				default: 'is-today'
			},
			checkedClass: {
				type: String, // 选中日期的样式class
				default: 'is-checked'
			},
			dotStyle: {
				type: Object, // 打点日期的自定义样式
				default () {
					return {
						background: '#c6c6c6'
					}
				}
			}
		},
		watch: {
			dotList: function(newvalue) {
				const days = this.days.slice(0);
				newvalue.forEach(item => {
					const index = days.findIndex(ditem => ditem.fullDate === item.date);
					if (index > 0) {
						days[index].info = item
					}
				});
				this.days = days;
			}
		},
		computed: {

			sheight() {
				// 根据年月判断有多少行
				// 判断该月有多少天
				let h = '70rpx';
				if (!this.weekMode) {
					const d = new Date(this.currentYear, this.currentMonth, 0);
					const days = d.getDate(); // 判断本月有多少天
					let day = new Date(d.setDate(1)).getDay();
					if (day === 0) {
						day = 7;
					}
					const pre = 8 - day;
					const rows = Math.ceil((days - pre) / 7) + 1;
					h = 70 * rows + 'rpx'
				}
				return h
			},
			timeStr() {
				let str = '';
				const nowd = new Date();
				const nowy = nowd.getFullYear();
				const d = new Date(this.currentYear, this.currentMonth - 1, this.currentDate);
				const y = d.getFullYear();
				// const m = (d.getMonth() + 1) <= 9 ? `0${d.getMonth()+1}` : d.getMonth() + 1;
				const m = d.getMonth() + 1;
				console.log()
				if (y == nowy) {
					str = `${m}月`;
				} else {
					str = `${y}年${m}月`;
				}
				return str;
			},
			predays() {
				let pres = [];
				if (this.weekMode) {
					const d = new Date(this.currentYear, this.currentMonth - 1, this.currentDate)
					d.setDate(d.getDate() - 7);
					pres = gegerateDates(d, 'week')
				} else {
					const d = new Date(this.currentYear, this.currentMonth - 2, 1)
					pres = gegerateDates(d, 'month')
				}
				return pres;
			},
			nextdays() {
				let nexts = [];
				if (this.weekMode) {
					const d = new Date(this.currentYear, this.currentMonth - 1, this.currentDate)
					d.setDate(d.getDate() + 7);
					nexts = gegerateDates(d, 'week')
				} else {
					const d = new Date(this.currentYear, this.currentMonth, 1)
					nexts = gegerateDates(d, 'month')
				}
				return nexts;
			},



		},
		data() {
			return {
				show_popup_center:false,
				user: [],
				showBackToTodayBtn: false,
				weeks: ['一', '二', '三', '四', '五', '六', '日'],
				current: 1,
				currentYear: '',
				currentMonth: '',
				currentDate: '',
				days: [],
				weekMode: true,
				swiper: [0, 1, 2],
				// dotList: [], // 打点的日期列表
				selectedDate: formatDate(new Date(), 'yyyy-MM-dd'),

				//下面的日历
				date: '',
				dots: [],

				// 周
				width: uni.getSystemInfoSync().windowWidth,
				height: uni.getSystemInfoSync().windowHeight,

				showChangeMode: true,
				nowWeek: 1,


				colorArrays: ['#70eb55', '#ffc450', '#ff9bd7', '#86affe', '#58eea4', '#ffa17d', '#1cbbb4', '#6964ad',
					'#d42245', '#218285'
				],
				showNotWeek: true,
				fullHeight: 0,
				arrList: ['全天', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21',
					'22', '23', '24',
				],
				arrThingsJson: [

				],
				habitArr: [],
				eventArr: [], //倒数日
				targetArr: [],
				matterArr: [],
				itemCheck:{}
			};
		},
		methods: {
			checkThisItem(item){
				this.itemCheck = item
				this.show_popup_center = true
				
			},
			getWeekList() {
				var _self = this
				var uri = getApp().globalData.url + 'modules/userView/getView?userId=' + _self.user.id + "&type=2" +
					"&time=" + _self.selectedDate
				console.log(uri)
				uni.request({
					url: uri,
					method: 'POST',
					header: {
						'content-type': 'application/json'
					},
					data: {

					},
					success: (res) => {
						var resData = res.data;
						console.log("===========getWeekList1==============")
						console.log(resData)
						if (resData.code == "200") {
							_self.arrThingsJson = []
							Object.keys(resData.data).forEach(function(key) {
								var value = resData.data[key]
								console.log(value)
								_self.arrThingsJson.push(value)
							});
							// console.log(_self.arrThingsJson)
						} else {

						}
					},
					fail: (err) => {

						uni.showToast({
							icon: 'none',
							title: '请求接口失败'
						})

					}
				});

			},
			changeSwp(e) {
				// console.log(e);
				const pre = this.current;
				const current = e.target.current;
				/* 根据前一个减去目前的值我们可以判断是下一个月/周还是上一个月/周 
				 *current - pre === 1, -2时是下一个月/周
				 *current -pre === -1, 2时是上一个月或者上一周
				 */
				this.current = current;
				if (current - pre === 1 || current - pre === -2) {
					this.daysNext();
				} else {
					this.daysPre();
				}
			},
			// 初始化日历的方法
			initDate(cur) {
				let date = ''
				if (cur) {
					date = new Date(cur)
				} else {
					date = new Date()
				}
				this.currentDate = date.getDate() // 今日日期 几号
				this.currentYear = date.getFullYear() // 当前年份
				this.currentMonth = date.getMonth() + 1 // 当前月份
				this.currentWeek = date.getDay() === 0 ? 7 : date.getDay() // 1...6,0   // 星期几
				const nowY = new Date().getFullYear() // 当前年份
				const nowM = new Date().getMonth() + 1
				const nowD = new Date().getDate() // 今日日期 几号
				const nowW = new Date().getDay();
				this.selectedDate = formatDate(date, 'yyyy-MM-dd')
				this.days = [];
				let days = [];
				if (this.weekMode) {
					days = gegerateDates(date, 'week');
					// this.selectedDate = days[0].fullDate;
				} else {
					days = gegerateDates(date, 'month');
					// const sel = new Date(this.selectedDate.replace('-', '/').replace('-', '/'));
					// const isMonth = sel.getFullYear() === this.currentYear && (sel.getMonth() + 1) === this.currentMonth;
					// if(!isMonth) {
					// 	this.selectedDate = formatDate(new Date(this.currentYear, this.currentMonth-1,1), 'yyyy-MM-dd')
					// }
				}
				days.forEach(day => {
					const dot = this.dotList.find(item => {
						return dateEqual(item.date, day.fullDate);
					})
					if (dot) {
						day.info = dot;
					}
				})
				this.days = days;
				//  派发事件,时间发生改变
				let obj = {
					start: '',
					end: ''
				};
				if (this.weekMode) {
					obj.start = this.days[0].time;
					obj.end = this.days[6].time
				} else {
					const start = new Date(this.currentYear, this.currentMonth - 1, 1);
					const end = new Date(this.currentYear, this.currentMonth, 0);
					obj.start = start;
					obj.end = end;
				}

				var nowday = formatDate(new Date(), 'yyyy-MM-dd');
				var currentDate = new Date(nowday)
				var startDate = new Date(obj.start)
				var endDate = new Date(obj.end)
				endDate.setHours(23, 59, 59)
				if (currentDate >= startDate && currentDate <= endDate) {
					this.showBackToTodayBtn = false
				} else {
					this.showBackToTodayBtn = true
				}
				this.$emit('days-change', obj)
			},
			//  上一个
			daysPre() {
				if (this.weekMode) {
					const d = new Date(this.currentYear, this.currentMonth - 1, this.currentDate);
					d.setDate(d.getDate() - 7);
					this.initDate(d);
				} else {
					const d = new Date(this.currentYear, this.currentMonth - 2, 1);
					this.initDate(d);
				}
				this.getWeekList()
			},
			//  下一个
			daysNext() {
				if (this.weekMode) {
					const d = new Date(this.currentYear, this.currentMonth - 1, this.currentDate);
					d.setDate(d.getDate() + 7);
					this.initDate(d);
				} else {
					const d = new Date(this.currentYear, this.currentMonth, 1);
					this.initDate(d);
				}
				this.getWeekList()
			},
			changeMode() {
				const premode = this.weekMode;
				let isweek = false;
				if (premode) {
					isweek = !!this.days.find(item => item.fullDate === this.selectedDate)
				}
				this.weekMode = !this.weekMode;
				let d = new Date(this.currentYear, this.currentMonth - 1, this.currentDate)
				const sel = new Date(this.selectedDate.replace('-', '/').replace('-', '/'));
				const isMonth = sel.getFullYear() === this.currentYear && (sel.getMonth() + 1) === this.currentMonth;
				if ((this.selectedDate && isMonth) || isweek) {
					d = new Date(this.selectedDate.replace('-', '/').replace('-', '/'))
				}
				this.initDate(d)
			},
			// 点击日期
			clickItem(e) {
				this.selectedDate = e.fullDate;
				this.$emit('selected-change', e);
			},
			goback() {
				const d = new Date();
				this.initDate(d);
				this.getWeekList()
			}
		},
		created() {
			this.initDate();
			var that = this;
			//获取手机屏幕的高度，让其等于swiper的高度，从而使屏幕充满
			uni.getSystemInfo({
				success: function(res) {
					that.fullHeight = "height:" + res.windowHeight + "px";
					console.log(that.fullHeight)
				}
			});


		},
		mounted() {
			var _self = this

			uni.getStorage({
				key: 'user',
				success: function(res) {
					if (res.data) {
						_self.user = res.data
						setTimeout(function() {
							_self.getWeekList()
						}, 200);
					}
				},
				fail: function(e) {
					uni.navigateTo({
						url: '../login/login'
					});
				}
			})
		}
	}
</script>

<style lang="scss">
	.zzx-calendar {
		width: 100%;
		height: 100%;
		position: fixed;

		.calendar-heander {
			text-align: center;
			height: 60upx;
			line-height: 60upx;
			position: relative;
			font-size: 30upx;

			.back-today {
				position: absolute;
				right: 0;
				width: 100upx;
				height: 30upx;
				line-height: 30upx;
				font-size: 20upx;
				top: 15upx;
				border-radius: 15upx 0 0 15upx;
				color: #ffffff;
				background-color: #FF6633;
			}
		}

		.calendar-weeks {
			width: 100%;
			display: flex;
			flex-flow: row nowrap;
			height: 60upx;
			line-height: 60upx;
			justify-content: center;
			align-items: center;
			font-size: 30upx;

			.calendar-week {
				width: calc(100% / 7);
				height: 100%;
				text-align: center;
			}
		}

		swiper {
			width: 100%;

		}

		.calendar-content {
			// min-height: 60upx;
		}

		.calendar-swiper {
			// min-height: 70upx;
			// transition: height ease-out 0.3s;
		}

		.calendar-item {
			margin: 0;
			padding: 0;
			height: 100%;
		}

		.calendar-days {
			width: 100%;
			display: flex;
			flex-flow: row nowrap;
			height: 70upx;
			line-height: 70upx;
			justify-content: center;
			align-items: center;
			font-size: 30upx;

			.calendar-day {
				width: calc(100% / 7);
				text-align: center;

			}
		}

		.day-hidden {
			visibility: hidden;
		}

		.mode-change {
			display: flex;
			justify-content: center;
			margin-top: 10upx;

			.mode-arrow-top {
				width: 0;
				height: 0;
				border-left: 12upx solid transparent;
				border-right: 12upx solid transparent;
				border-bottom: 10upx solid #FF6633;
			}

			.mode-arrow-bottom {
				width: 0;
				height: 0;
				border-left: 12upx solid transparent;
				border-right: 12upx solid transparent;
				border-top: 10upx solid #FF6633;
			}
		}

		.is-today {
			background: #ffffff;
			// border: 1upx solid #FF6633;
			border-radius: 50%;
			color: #FF6633;
		}

		.is-checked {
			background: #FF6633;
			color: #ffffff;
		}

		.date {
			width: 50upx;
			height: 50upx;
			line-height: 50upx;
			margin: 0 auto;
			border-radius: 50upx;
		}

		.dot-show {
			margin-top: 4upx;
			width: 10upx;
			height: 10upx;
			background: #c6c6c6;
			border-radius: 10upx;
		}
	}


	.kcb-item {
		position: absolute;
		justify-content: center;
		display: flex;
		border-radius: 5px;
		background-size: 400% 400%;
		animation: Change 2s ease infinite;
	}

	.hx {
		position: absolute;
		display: flex;
		border-bottom: 1px dashed #a3a3a3;
		left: 0;
		right: 0;
	}

	.sx {
		position: absolute;
		display: flex;
		/* border-left: 1px dashed #a3a3a3; */
	}

	.smalltext {
		display: block;
		color: #fff;
		font-size: 24rpx;
		font-weight: bolder;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.left {
		justify-content: center;
		display: flex;
		flex-direction: column;
		align-items: center;
		color: black;
	}

	.text-center {
		display: flex;
		align-items: center;
		justify-content: center;
		text-align: center;
	}

	.top {
		display: flex;
		flex-direction: column;
		color: black;
		align-items: center;
		position: fixed;
		background: #fff;
		z-index: 1;
		border-bottom: 1rpx solid #a3a3a3;
		font-size: 30rpx;
	}

	.top-text {
		justify-content: center;
		display: flex;
		align-items: center;
		height: 25px;
	}

	.backimg {
		width: 100%;
		z-index: -1;
		position: fixed;
	}

	.week {
		display: flex;
		width: 100%;
		flex-direction: row;
		align-items: center;
		justify-content: center;
		padding: 1rpx;
		height: 30px;
	}

	.weeks {
		width: 100vw;
		height: 100vh;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		background: rgba(0, 0, 0, 0.5);
		position: fixed;
		z-index: 2;
	}

	.week-top {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		background: #39b54a;
		color: #ffffff;
		padding: 25rpx 0;
		border-radius: 10rpx 10rpx 0 0;
	}

	.week-bt {
		display: flex;
		background: #f0f0f0;
		margin: 5rpx;
		padding: 8rpx 5rpx;
		width: 120rpx;
		align-items: center;
		justify-content: center;
		border-radius: 5rpx;
		font-size: 25rpx;
	}


	.write_btn {
		position: fixed;
		bottom: 15vh;
		right: 50rpx;
		width: 100rpx;
		height: 100rpx;
		border-radius: 50rpx;
		background-color: #FE6601;
		z-index: 100;
		display: flex;

		.icon {
			justify-content: center;
			width: 100%;
			color: #FFFFFF;
			font-size: 50rpx;
			/* #ifdef MP-TOUTIAO */
			// 头条小程序 没居中
			text-align: center;
			padding: 15rpx 0;
			/* #endif */
		}
	}

	.swiper_item {
		height: 100%;
		width: 100%;
		float: left;
	}

	.itemTd {
		// border-radius: 4px;
		// text-align: center;
		// height: 20px;
		// line-height: 20px;
		// color: white;
		// width: 98%;
		// margin-top: 1px;
		// font-size: 9px;
		// margin-left: 1%;
		background-color: #18B998;
		overflow: hidden;
		border-radius: 2px;
		text-align: left;
		height: 20px;
		line-height: 20px;
		color: #7B7B7B;
		width: 96%;
		margin-top: 2px;
		font-size: 9px;
		margin-left: 2%;
		padding-left: 2px;
		
	}

	/* 日历顶部信息 */
	.calendar_info {
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		line-height: 30px;

	}

	.calendar_info .title {
		font-size: 18px;
		font-weight: bold;
		font-family: 'Times New Roman', Times, serif;
		z-index: 999;
	}

	.calendar_info .desc {
		margin-left: 29rpx;
		font-size: 28rpx;
		color: #959595;
	}

	.calendar_info .backToToday {
		margin-left: auto;
		font-size: 24rpx;
	}

	/* 日历顶部信息 */

	.itembox {
		width: calc(100% / 7);
		float: left;
		min-height: 60px;
		text-align: center;
	}
	.linethrough{
		text-decoration: line-through;
		
	}
	.opacityClass{
		opacity: 0.5;
	}
	.container {
		padding: 20px;
	}
	
	.row {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		margin: -10px;
	}
	
	.category-item {
		width: 49%;
		margin-bottom: 8px;
		display: flex;
		flex-direction: row;
		align-items: center;
		padding: 10px;
		background-color: #FFFFFF;
		border-radius: 8px;
		cursor: pointer;
		transition: background-color 0.3s ease;
		height: 110rpx;
		text-align: center;
	}
	
	.category-icon {
		width: 40px;
		height: 40px;
		margin-right: 10px;
	}
	
	.category-name {
		font-size: 14px;
	}
	
	.save_btn {
		text-align: right;
		background-color: #18B998 !important;
		color: white;
	}
</style>